package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties; // 读取yml文件

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserLoginVO loginByOpenid(UserLoginDTO userLoginDTO) {
        UserLoginVO userLoginVO = new UserLoginVO();
        // 1.获取openid:根据临时凭证code,去微信那边获取用户的openid
        // 获取openid的条件：访问路径，准备参数，使用HttpClient
        String openId = getOpenId(userLoginDTO.getCode());
        // 2.如果openid是空，抛出业务异常
        if(openId == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        // 3.判断openid,是否在数据库存在
           // 调用mapper,根据openid查询用户,如果查询到，返回User对象
        // 3.1 存在，说明已登录，返回实体对象User
        User user = userMapper.selectByOpenId(openId);
        // 3.2 不存在，使用openid,注册一个用户
        if(user == null){
            // 不存在，就是注册一个用户，需要用到一个实体类对象
            user = new User();
            user.setOpenid(openId);
            user.setCreateTime(LocalDateTime.now());
            // 插入成功后，需要返回主键
            userMapper.insertUser(user);
        }

        // 生成token
        Map<String,Object> payload = new HashMap<>();
        payload.put(JwtClaimsConstant.USER_ID,user.getId());
        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), payload);


        // 4.生成token,封装VO对象（id,openid,token）
        userLoginVO.setId(user.getId());
        userLoginVO.setToken(jwt);
        userLoginVO.setOpenid(openId);

        return userLoginVO;
    }

    private String getOpenId(String code) {
        // 使用httpclient
        Map paramData = new HashMap();
        paramData.put("appid",weChatProperties.getAppid());
        paramData.put("secret",weChatProperties.getSecret());
        paramData.put("js_code",code);
        paramData.put("grant_type","authorization_code");
        log.info("参数：{}",paramData);
        String content = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", paramData);
        // 返回的是JSON串，我们需要是openid
        log.info("微信返回:{}",content);
        JSONObject jsonObject = JSON.parseObject(content);
        String openid = jsonObject.getString("openid");
        return openid;
    }


}
